package com.tyl.filter;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.tyl.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
//交给spring容器
public class CheckTokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //当请求过来时就经过这个过滤器

        //先获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String url = request.getURI().toString();
        if (url.indexOf("/user/")>-1){
            return chain.filter(exchange);
        }
        //获取请求中头部信息
        HttpHeaders headers = request.getHeaders();
        //获取头部信息中token的键对应的值
        List<String> authorization = headers.get("Authorization");
        if (authorization != null &&authorization.size()>0 ) {
            //表示数据不为空那么就可以通过请求
            //返回时一个数组我们就传一个数据那么就可以拿到下标为一的数据
            String token = authorization.get(0);
            //验证token
            try {
                JwtUtil.verify(token);
                //方形请求
                chain.filter(exchange);
            } catch (Exception e) {
                e.printStackTrace();
                //响应状态给响应设置一个错误的状态
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
        }else {

        }
        return chain.filter(exchange);
        //表示通过请求
    }

    @Override
    public int getOrder() {
        return 0;
        //先后顺序数字越小越靠前
    }
}
